<?php
require './vendor/autoload.php';
// 获取ip地址
function getIpAddress($ips)
{
    import('Org.Util.iplocate', '', '.php');
    if ($ips == '127.0.0.1' || $ips == '0.0.0.0')
        $data = '本地地址';
    else {
        $ip = new \iplocate();
        $data = $ip->getaddress($ips);
    }
    return $data['area1'] . $data['area2'];
}

/*
 * 删除缓存方法
 */
function delFileByDir($dir)
{
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {

            $fullpath = $dir . "/" . $file;
            if (is_dir($fullpath)) {
                delFileByDir($fullpath);
            } else {
                unlink($fullpath);
            }
        }
    }
    closedir($dh);
}


/*根据id获取头像
 * */
function get_nickname($userid)
{
    $userinfo = M('user')->where("id = $userid")->find();
    if ($userinfo['nickname']) {
        return $userinfo['nickname'];
    } else {
        return false;
    }
}

/*post请求获取数据*/
function curlPost($url, $timeout = 5)
{
    if (function_exists('file_get_contents')) {
        $optionget = array('http' => array('method' => "GET", 'header' => "User-Agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.0.04506; CIBA)\r\nAccept:*/*\r\nReferer:https://kyfw.12306.cn/otn/lcxxcx/init"));
        $file_contents = file_get_contents($url, false, stream_context_create($optionget));
    } else {
        $ch = curl_init();
        $header = array('Accept:*/*', 'Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding:gzip,deflate,sdch', 'Accept-Language:zh-CN,zh;q=0.8,ja;q=0.6,en;q=0.4', 'Connection:keep-alive', 'Host:kyfw.12306.cn', 'Referer:https://kyfw.12306.cn/otn/lcxxcx/init',);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
    }
    $file_contents = json_decode($file_contents, true);
    return $file_contents;
}

/*get请求获取数据*/
function curlGet($url)
{
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    return $output;
}


/*
	中国国情下的判断浏览器类型，简直就是五代十国，乱七八糟，对博主的收集表示感谢

	参考：
	http://www.cnblogs.com/wangchao928/p/4166805.html
	http://www.useragentstring.com/pages/Internet%20Explorer/
	https://github.com/serbanghita/Mobile-Detect/blob/master/Mobile_Detect.php

	Mozilla/4.0 (compatible; MSIE 5.0; Windows NT)
	Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
	Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)
	Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)

	Win7+ie9：
	Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; Tablet PC 2.0; .NET4.0E)

	win7+ie11，模拟 78910 头是一样的
	mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko

	Win7+ie8：
	Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)

	WinXP+ie8：
	Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB7.0)

	WinXP+ie7：
	Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)

	WinXP+ie6：
	Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)

	傲游3.1.7在Win7+ie9,高速模式:
	Mozilla/5.0 (Windows; U; Windows NT 6.1; ) AppleWebKit/534.12 (KHTML, like Gecko) Maxthon/3.0 Safari/534.12

	傲游3.1.7在Win7+ie9,IE内核兼容模式:
	Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)

	搜狗
	搜狗3.0在Win7+ie9,IE内核兼容模式:
	Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)

	搜狗3.0在Win7+ie9,高速模式:
	Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.33 Safari/534.3 SE 2.X MetaSr 1.0

	360
	360浏览器3.0在Win7+ie9:
	Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)

	QQ 浏览器
	QQ 浏览器6.9(11079)在Win7+ie9,极速模式:
	Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1 QQBrowser/6.9.11079.201

	QQ浏览器6.9(11079)在Win7+ie9,IE内核兼容模式:
	Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E) QQBrowser/6.9.11079.201

	阿云浏览器
	阿云浏览器 1.3.0.1724 Beta 在Win7+ie9:
	Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)

	MIUI V5
	Mozilla/5.0 (Linux; U; Android <android-version>; <location>; <MODEL> Build/<ProductLine>) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 XiaoMi/MiuiBrowser/1.0
*/
function get__browser()
{
    // 默认为 chrome 标准浏览器
    $browser = array(
        'device' => 'pc', // pc|mobile|pad
        'name' => 'chrome', // chrome|firefox|ie|opera
        'version' => 30,
    );
    $agent = $_SERVER['HTTP_USER_AGENT'];
    // 主要判断是否为垃圾 IE6789
    if (strpos($agent, 'msie') !== FALSE || stripos($agent, 'trident') !== FALSE) {
        $browser['name'] = 'ie';
        $browser['version'] = 8;
        preg_match('#msie\s*([\d\.]+)#is', $agent, $m);
        if (!empty($m[1])) {
            if (strpos($agent, 'compatible; msie 7.0;') !== FALSE) {
                $browser['version'] = 8;
            } else {
                $browser['version'] = intval($m[1]);
            }
        } else {
            // 匹配兼容模式 Trident/7.0，兼容模式下会有此标志 $trident = 7;
            preg_match('#Trident/([\d\.]+)#is', $agent, $m);
            if (!empty($m[1])) {
                $trident = intval($m[1]);
                $trident == 4 AND $browser['version'] = 8;
                $trident == 5 AND $browser['version'] = 9;
                $trident > 5 AND $browser['version'] = 10;
            }
        }
    }

    if (isset($_SERVER['HTTP_X_WAP_PROFILE']) || (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap") || stripos($agent, 'phone') || stripos($agent, 'mobile') || strpos($agent, 'ipod'))) {
        $browser['device'] = 'mobile';
    } elseif (strpos($agent, 'pad') !== FALSE) {
        $browser['device'] = 'pad';
        $browser['name'] = '';
        $browser['version'] = '';
        /*
        } elseif(strpos($agent, 'miui') !== FALSE) {
            $browser['device'] = 'mobile';
            $browser['name'] = 'xiaomi';
            $browser['version'] = '';
        */
    } else {
        $robots = array('bot', 'spider', 'slurp');
        foreach ($robots as $robot) {
            if (strpos($agent, $robot) !== FALSE) {
                $browser['name'] = 'robot';
                return $browser;
            }
        }
    }
    return $browser;
}


/*
 * 生成二维码
 * */
function qrcode($url, $level = 3, $size = 4)
{
    Vendor('phpqrcode.phpqrcode');
    $errorCorrectionLevel = intval($level);//容错级别
    $matrixPointSize = intval($size);//生成图片大小
    //生成二维码图片
    //echo $_SERVER['REQUEST_URI'];
    $object = new \QRcode();

    $date = date('Y-m-d');
    $path = "Uploads/qrcode/" . $date . '/';
    if (!file_exists($path)) {
        mkdir("$path", 0777, true);
    }
    $name = time() . '_' . mt_rand();
    //生成的文件名
    $fileName = $path . $name . '.png';
    $res = $object->png($url, $fileName, $errorCorrectionLevel, $matrixPointSize, 2);
    return $fileName;
}

/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function & load_wechat($type = '')
{
    !class_exists('Wechat\Loader', FALSE) && Vendor('Wechat.Loader');
    static $wechat = array();
    $index = md5(strtolower($type));
    if (!isset($wechat[$index])) {
        // 从数据库查询配置参数
        $res = C('WEIXINPAY_CONFIG');
        $config['appid'] = $res['APPID'];
        $config['appsecret'] = $res['APPSECRET'];
        $config['encodingaeskey'] = '';
        $config['mch_id'] = $res['MCHID'];
        $config['partnerkey'] = $res['KEY'];
        $config['ssl_cer'] = '';
        $config['ssl_key'] = '';
        $config['cachepath'] = '';

        // 设置SDK的缓存路径
        $config['cachepath'] = CACHE_PATH . 'Data/';
        $wechat[$index] = &\Wechat\Loader::get_instance($type, $config);
    }
    return $wechat[$index];
}

/**
 * @desc 文件上传
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @return array|bool
 */
function file_upload($type,$width=500)
{
    if (empty($_FILES)) {
        return showErrorMsg('没有文件上传',100002);
    } else {

        $upload = new \Think\Upload();// 实例化上传类

        switch ($type){
            case 'video':
                $upload->maxSize = 524288000;// 设置附件上传大小
                $upload->exts = array('mp4','flv');// 设置附件上传类型
                $upload->rootPath = './Uploads/'.$type.'/'; // 设置附件上传根目录
                $upload->savePath = ''; // 设置附件上传（子）目录
                $upload->saveRule = 'time';
                $upload->hash = true;
                $upload_ret = $upload->uploadOne($_FILES['file']);
                if ($upload_ret == false) return showErrorMsg($upload->getError(),100002);

                $imgUrl = empty($upload_ret) ? '' : '/Uploads/' .$type.'/'. $upload_ret['savepath'] . $upload_ret['savename'];

                $insert_data = array(
                    'uid' => decode_token(),
                    'name' => $_FILES['file']['name'],
                    'path' => $imgUrl,
                    'ext' => $_FILES['file']['type'],
                    'size' => $_FILES['file']['size'],
                    'md5' => $upload_ret['md5'],
                    'sha1' => $upload_ret['sha1'],
                    'location' => 'location',
                    'download' => '0',
                    'url' => C('site_url') . $imgUrl,
                    'thumb' => '/Uploads/photo/' . $upload_ret['savepath'] . '500-' . $upload_ret['savename'],
                    'create_time' => NOW_TIME,
                    'update_time' => NOW_TIME,
                );

                $operation = M('file')->add($insert_data);

                $upload_ret['url'] = $imgUrl;
                $upload_ret['domain_url'] = C('site_url').$imgUrl;

                break;
            case 'photo':
                $upload->maxSize = 524288000;// 设置附件上传大小
                $upload->exts = array('jpg','gif','jpeg','png');// 设置附件上传类型
                $upload->rootPath = './Uploads/'.$type.'/'; // 设置附件上传根目录
                $upload->savePath = ''; // 设置附件上传（子）目录
                $upload->saveRule = 'time';
                $upload->hash = true;
                $upload_ret = $upload->uploadOne($_FILES['file']);
                if ($upload_ret == false) return showErrorMsg($upload->getError(),100002);

                $imgUrl = empty($upload_ret) ? '' : '/Uploads/' .$type.'/'. $upload_ret['savepath'] . $upload_ret['savename'];

                thumb($imgUrl, $width, '/Uploads/'.$type.'/' . $upload_ret['savepath'] . $width.'-' . $upload_ret['savename']);

                $insert_data = array(
                    'uid' => decode_token(),
                    'name' => $_FILES['file']['name'],
                    'path' => $imgUrl,
                    'ext' => $_FILES['file']['type'],
                    'size' => $_FILES['file']['size'],
                    'md5' => $upload_ret['md5'],
                    'sha1' => $upload_ret['sha1'],
                    'location' => 'location',
                    'download' => '0',
                    'url' => C('site_url') . $imgUrl,
                    'thumb' => '/Uploads/photo/' . $upload_ret['savepath'] . '500-' . $upload_ret['savename'],
                    'create_time' => NOW_TIME,
                    'update_time' => NOW_TIME,
                );

                $operation = M('file')->add($insert_data);


                $upload_ret['url_size'] =  '/Uploads/'.$type.'/' . $upload_ret['savepath'] . $width.'-' . $upload_ret['savename'];
                $upload_ret['domain_url_size'] =  '/Uploads/'.$type.'/' . $upload_ret['savepath'] . $width.'-' . $upload_ret['savename'];

                $upload_ret['url'] = $imgUrl;
                $upload_ret['domain_url'] = C('site_url').$imgUrl;

                break;
            case 'doc':
                $upload->maxSize = 524288000;// 设置附件上传大小
                $upload->exts = array('doc','ppt','docx','pptx','zip');// 设置附件上传类型
                $upload->rootPath = './Uploads/'.$type.'/'; // 设置附件上传根目录
                $upload->savePath = ''; // 设置附件上传（子）目录
                $upload->saveRule = 'time';
                $upload_ret = $upload->uploadOne($_FILES['file']);
                if ($upload_ret == false) return showErrorMsg($upload->getError(),100002);


                $imgUrl = empty($upload_ret) ? '' : '/Uploads/' .$type.'/'. $upload_ret['savepath'] . $upload_ret['savename'];

                $insert_data = array(
                    'uid' => decode_token(),
                    'name' => $_FILES['file']['name'],
                    'path' => $imgUrl,
                    'ext' => $_FILES['file']['type'],
                    'size' => $_FILES['file']['size'],
                    'md5' => $upload_ret['md5'],
                    'sha1' => $upload_ret['sha1'],
                    'location' => 'location',
                    'download' => '0',
                    'url' => C('site_url') . $imgUrl,
                    'thumb' => '/Uploads/photo/' . $upload_ret['savepath'] . '500-' . $upload_ret['savename'],
                    'create_time' => NOW_TIME,
                    'update_time' => NOW_TIME,
                );
                $operation = M('file')->add($insert_data);

                $upload_ret['url'] = $imgUrl;
                $upload_ret['domain_url'] = C('site_url').$imgUrl;

                break;
        }
        return showErrorMsg(L('_OPERATION_SUCCESS_'),0,2,$upload_ret);
    }
}

/**
 * @desc 缩略图
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param      $img_path
 * @param int  $thumb_w
 * @param      $save_path
 * @param bool $is_del
 */
function thumb($img_path, $thumb_w = 300, $save_path, $is_del = false)
{
    $image = new \Think\Image();

    $img_path = '.'.$img_path;
    $save_path = '.'.$save_path;

    $r = $image->open($img_path);

    $width = $image->width(); // 返回图片的宽度
    if ($width > $thumb_w) {
        $width = $width / $thumb_w; //取得图片的长宽比
        $height = $image->height();
        $thumb_h = ceil($height / $width);
    }
    //如果文件路径不存在则创建
    $save_path_info = pathinfo($save_path);
    if (!is_dir($save_path_info['dirname'])) mkdir($save_path_info['dirname'], 0777);
    $ret = $image->thumb($thumb_w, $thumb_h)->save($save_path);
    if ($is_del) @unlink($img_path); //删除源文件
}

/**
 * @desc
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param       $msg
 * @param int   $error
 * @param int   $return_type
 * @param array $return_data
 * @param int   $page_info
 * @return array
 */
function showErrorMsg($msg, $error = 0, $return_type = 0, $return_data = array(), $page_info = 0)
{
    if ($error == -1) {
        $RetData = $msg;
    } elseif ($error == 0) {
        $RetData = array(
            'error' => $error,
            'error_msg' => $msg,
            'return_type' => $return_type,
            'return_data' => $return_data,
            'page_info' => $page_info,
            'status' => 2,
        );
    } else {
        $RetData = array(
            'error' => $error,
            'error_msg' => $msg,
            'status' => 3,
            'return_type' => $return_type,
            'return_data' => $return_data,
            'page_info' => $page_info
        );
    }
    return $RetData;
    die();
}

/**
 * 分页函数
 * @param $model
 * @param $map
 * @param $p |开始页数
 * @param $listRows |每页行数
 * @param $order |排序
 * @param $field |字段
 */
function _listPage($model, $map = null, $p = 1, $order = null, $field = null, $listRows = 10, $group = null,$join = '')
{
    //设置条数
    $listRows = $listRows;
    $group = $group;
    if (empty($field)) $field = '*';

    if (empty($group)) {
        if (!empty($join)){
            // 查询满足要求的总记录数
            $count = $model->join($join)->where($map)->count();
            $Page = new \Think\Page($count, $listRows);
            //设置条数
            $p_start = isset($p) ? ($p - 1) * $listRows : $Page->firstRow;
            $list = $model->field($field)->join($join)->where($map)->limit($p_start . ',' . $Page->listRows)->order($order)->select();
        }else{
            // 查询满足要求的总记录数
            $count = $model->where($map)->count();
            $Page = new \Think\Page($count, $listRows);
            //设置条数
            $p_start = isset($p) ? ($p - 1) * $listRows : $Page->firstRow;
            $list = $model->field($field)->where($map)->limit($p_start . ',' . $Page->listRows)->order($order)->select();
        }

    } else {
        if (!empty($join)){
            // 查询满足要求的总记录数
            $count = count($model->field($field)->join($join)->where($map)->group($group)->select());
            $Page = new \Think\Page($count, $listRows);
            //设置条数
            $p_start = isset($p) ? ($p - 1) * $listRows : $Page->firstRow;
            $list = $model->field($field)->join($join)->where($map)->limit($p_start . ',' . $Page->listRows)->order($order)->group($group)->select();

        }else{
            // 查询满足要求的总记录数
            $count = count($model->field($field)->where($map)->group($group)->select());
            $Page = new \Think\Page($count, $listRows);
            //设置条数
            $p_start = isset($p) ? ($p - 1) * $listRows : $Page->firstRow;
            $list = $model->field($field)->where($map)->limit($p_start . ',' . $Page->listRows)->order($order)->group($group)->select();

        }
    }
    if ($list == false) {
//        var_dump($model->getDBError());
//        return showErrorMsg($model->getDBError(),10002);
    }
//    if (!empty($list)) {
//        foreach ($list as &$val) {
//            if (isset($val['create_time'])) {
//                $val['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
//            }
//        }
//    }

    $page = array(
        'total' => (int)$count,
        'count' => (int)count($list),
        'listRows' => (int)$listRows,
        'p' => (int)$p
    );
    return array($list, $page);
}

/**
 * @desc 返回列表数据
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $listRet
 * @param $page
 * @return array
 */
function showList($listRet, $page)
{
    if (empty($listRet)) {
        $ReData = array(
            'status' => 2,
            'error' => 0,
            'error_msg' => L('_OPERATION_SUCCESS_'),
            'return_type' => 1,
            'return_data' => array(),
            'page_info' => empty($page) ? new \stdClass() : $page
        );
    } else {
        $ReData = array(
            'error_msg' => L('_OPERATION_SUCCESS_'),
            'status' => 2,
            'return_type' => 1,
            'return_data' => $listRet,
            'page_info' => $page
        );
    }
    return $ReData;
}

//apache and nginx diff
if (!function_exists('getallheaders')) {
    function getallheaders()
    {
        $headers = array();
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

/**
 * @desc
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param int    $user_type
 * @param        $user_id
 * @param        $type
 * @param        $amount
 * @param        $code 1 系统充值增加余额
 * @param        $status
 * @param string $beizhu
 * @param        $scene 1飞妈，2游艇
 * @return bool$user_id, $type,$title = '系统通知',$content, $send_user_id = 0
 */
function money_record($uid, $amount,$beizhu = '无备注',$type, $code, $status, $scene, $puid)
{
    $insert_data = array(
        'uid'       =>  $uid,
        'puid'      =>  $puid,
        'type'      =>  $type,
        'amount'    =>  $amount,
        'code'      =>  $code,
        'status'    =>  $status,
        'beizhu'    =>  $beizhu,
        'scene'     =>  $scene,
        'create_time'   =>  NOW_TIME
    );
    $money_record_res = M('money_record')->add($insert_data);

    if ($money_record_res) {
        return true;
    } else {
        return false;
    }
}


/**
 * @desc 站内信记录
 * @author Egor<http://gitee.com/seosite>
 * @param        $user_id
 * @param        $type
 * @param string $title
 * @param        $content
 * @param int    $send_user_id
 * @return bool
 */
function message_record($user_id, $type,$title = '系统通知',$content, $send_user_id = 0)
{
//    $pushObj = new \Home\Controller\PushController();

    $insert_data = array(
        'uid'           =>  $user_id,
        'send_uid'      =>  $send_user_id,
        'title'         =>  $title,
        'content'       =>  $content,
        'is_red'        =>  0,
        'type'          =>  $type,
        'create_time'   =>  NOW_TIME
    );

    $message_res = M('message')->add($insert_data);

    if ($message_res) {
        return true;
    } else {
        return false;
    }
}

//上传图片
function imgupload($base64img)
{
    $base64_image = str_replace(' ', '+', $base64img);
    //post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)) {
        //匹配成功
        if ($result[2] == 'jpeg') {
            $image_name = uniqid() . '.jpg';
        } else {
            $image_name = uniqid() . '.' . $result[2];
        }

        $save_path = "./Uploads/photo/" . date('Y-m-d') . "/";
        if (!is_dir($save_path)) mkdir($save_path, 0777);

        $image_file = "{$save_path}{$image_name}";
        //服务器文件存储路径
        if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))) {
            thumb($image_file, 500, "{$save_path}" . "/500-{$image_name}");
            thumb($image_file, 800, "{$save_path}" . "/800-{$image_name}");
            $insert_data = array(
                'uid' => decode_token(),
                'name' => $image_name,
                'path' => $image_file,
                'ext' => '',
                'size' => '',
                'md5' => md5($base64_image),
                'sha1' => sha1($base64_image),
                'base64' => $base64_image,
                'location' => 'location',
                'download' => '0',
                'url' => C('site_url') . $save_path . '500-' . $image_name,
                'thumb' => $save_path . '500-' . $image_name,
                'create_time' => NOW_TIME,
                'update_time' => NOW_TIME,
            );
            $insert_id = M('file')->add($insert_data);

//            var_dump($insert_id);

            $imgPath = "/Uploads/photo/" . $image_name;
            $ReData['code'] = '200';//相应状态吗
            $ReData['msg'] = '上传成功';
            $ReData['data']['path'] = $insert_data['thumb'];
        } else {

            $ReData['code'] = '-200';//相应状态吗
            $ReData['msg'] = '上传失败';
            $ReData['data']['base64img'] = $base64img;
        }
    } else {
        $ReData['code'] = '-400';//相应状态吗
        $ReData['msg'] = '传输数据格式错误';
        $ReData['data']['base64img'] = $base64img;
    }
    return $ReData;
}

/**
 * @desc 返回汉字首字母
 * @param $str
 * @return null|string
 */
function getInitials($str)
{
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) {
        return strtoupper($str{0});
    }

    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) {
        return 'A';
    }

    if ($asc >= -20283 && $asc <= -19776) {
        return 'B';
    }

    if ($asc >= -19775 && $asc <= -19219) {
        return 'C';
    }

    if ($asc >= -19218 && $asc <= -18711) {
        return 'D';
    }

    if ($asc >= -18710 && $asc <= -18527) {
        return 'E';
    }

    if ($asc >= -18526 && $asc <= -18240) {
        return 'F';
    }

    if ($asc >= -18239 && $asc <= -17923) {
        return 'G';
    }

    if ($asc >= -17922 && $asc <= -17418) {
        return 'H';
    }

    if ($asc >= -17417 && $asc <= -16475) {
        return 'J';
    }

    if ($asc >= -16474 && $asc <= -16213) {
        return 'K';
    }

    if ($asc >= -16212 && $asc <= -15641) {
        return 'L';
    }

    if ($asc >= -15640 && $asc <= -15166) {
        return 'M';
    }

    if ($asc >= -15165 && $asc <= -14923) {
        return 'N';
    }

    if ($asc >= -14922 && $asc <= -14915) {
        return 'O';
    }

    if ($asc >= -14914 && $asc <= -14631) {
        return 'P';
    }

    if ($asc >= -14630 && $asc <= -14150) {
        return 'Q';
    }

    if ($asc >= -14149 && $asc <= -14091) {
        return 'R';
    }

    if ($asc >= -14090 && $asc <= -13319) {
        return 'S';
    }

    if ($asc >= -13318 && $asc <= -12839) {
        return 'T';
    }

    if ($asc >= -12838 && $asc <= -12557) {
        return 'W';
    }

    if ($asc >= -12556 && $asc <= -11848) {
        return 'X';
    }

    if ($asc >= -11847 && $asc <= -11056) {
        return 'Y';
    }

    if ($asc >= -11055 && $asc <= -10247) {
        return 'Z';
    }

    return null;
}

function get_loclist_id($lat, $lng)
{
//    $lat = $baiduInfo['result']['location']['lat'];//维度
//    $lng = $baiduInfo['result']['location']['lng'];//进度

    $location_url = "http://api.map.baidu.com/geocoder/v2/?callback=&location={$lat},{$lng}&output=json&pois=0&ak=Hxi2Wh9hARPxWE7OhP0MPvIoPFY3Y0KY";

    $locationJson = file_get_contents($location_url);
    $locationInfo = json_decode($locationJson, true);

    if ($locationInfo['status'] != 0) return showErrorMsg($locationInfo['message'], 100097);

//    $province = $locationInfo['result']['addressComponent']['province'];
//    $city = $locationInfo['result']['addressComponent']['city'];


    return $locationInfo['result']['addressComponent'];
}

function getRoomID($type)
{
    $room_id = \lyf\Str::randString(6, 1);

    if ($type == 1) {//视频直播
        $room_id = 'CJ_Video' . $room_id;
        $is_exist = M('direct')->where(['room_id' => $room_id])->find();
        if ($is_exist) {
            getRoomID($type);
        }
    } elseif ($type == 2) {//音频
        $room_id = 'CJ_Audio' . $room_id;
        $is_exist = M('audio')->where(['room_id' => $room_id])->find();
        if ($is_exist) {
            getRoomID($type);
        }
    }elseif ($type==3){//会议
        $room_id = 'CJ_Meets' . $room_id;
        $is_exist = M('meeting')->where(['room_id' => $room_id])->find();
        if ($is_exist) {
            getRoomID($type);
        }
    }


    return $room_id;

}

/**
 * @desc 返回图片地址
 * @param $key
 * @return array|string
 */
function getUrlByOssKey($key)
{
    if (empty($key)) return showErrorMsg('文件名称不能为空', 100002);

    $obj = new \JohnLui\AliyunOSS($city = '北京', $networkType = '经典网络', $isInternal = false, 'LTAII2PxcaxG6mQj', 'evXoGHHZRH434khoZSgYIe6Jn1PRnb');
    $obj->setBucket('cjzb');
    $date = new \DateTime('+1 days');
    $url = $obj->getUrl($key, $date);


    $obj = new \JohnLui\AliyunOSS(C('oss.city'), C('oss.networkType'), $isInternal = false, C('oss.AccessKeyId'), C('oss.AccessKeySecret'));

    $obj->setBucket('cjzb');


    $date = new \DateTime('+1 days');

    $acl_url = $obj->getUrl($key, $date);

    return urldecode($acl_url);
}

/**
 * @desc 发送短信
 * @param     $phone
 * @param     $type
 * @param int $uid
 * @return array
 */
function sendAliSms($phone, $type, $code)
{

    $params = array();
    $accessKeyId = C('oss.AccessKeyId');
    $accessKeySecret = C('oss.AccessKeySecret');
    $params["PhoneNumbers"] = $phone;
    $params["SignName"] = "赫桥财经";

    if (empty($phone)) return showErrorMsg('手机号不能为空', 100002);

    switch ($type) {
        case 1://注册
//            if ($userInfo) return showErrorMsg('手机号已被注册',100002);
            $TemplateCode = 'SMS_86940367';
            break;
        case 2://修改密码
//            if (!$userInfo) return showErrorMsg('手机号未被注册',100002);
            $TemplateCode = 'SMS_86940366';
            break;
        default://默认其他短信
            $TemplateCode = 'SMS_86940371';
            break;
    }
    $params["TemplateCode"] = $TemplateCode;//SMS_86940371

    $params['TemplateParam'] = Array(
        "code" => $code
    );

    // fixme 可选: 设置发送短信流水号
//    $params['OutId'] = "12345";

    // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
//    $params['SmsUpExtendCode'] = "1234567";


    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
    if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
    }

    Vendor('dysms.SignatureHelper');
    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
    $helper = new \Aliyun\DySDKLite\SignatureHelper();

    // 此处可能会抛出异常，注意catch
    $content = $helper->request(
        $accessKeyId,
        $accessKeySecret,
        "dysmsapi.aliyuncs.com",
        array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "SendSms",
            "Version" => "2017-05-25",
        ))
    // fixme 选填: 启用https
    // ,true
    );
    if ($content->Code !== 'OK') return showErrorMsg('阿里大鱼：' . $content->Message, 100099);

    return true;
}


function get_post_vars()
{
    return empty(I('post.')) ? array() : I('post.');
}

function get_param_vars()
{
    return empty(I('post.param')) ? array() : json_decode($_POST['param'],true);
}


//加密函数
function lock_url($txt,$key='Finance_Direct')
{
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=-";
    $nh = rand(0,66);
    $ch = $chars[$nh];
    $mdKey = md5($key.$ch);
    $mdKey = substr($mdKey,$nh%8, $nh%8+7);
    $txt = base64_encode($txt);
    $tmp = '';
    $i=0;$j=0;$k = 0;
    for ($i=0; $i<strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%66;
        $tmp .= $chars[$j];
    }
    return $ch.$tmp;
//    return urlencode($ch.$tmp);
}
//解密函数
function unlock_url($txt,$post_key)
{
    if (empty($post_key)) return false;
    if ($post_key!==C('Unlock_KEY')) return false;

//    $txt = urldecode($txt);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=-";
    $ch = $txt[0];
    $nh = strpos($chars,$ch);
    $mdKey = md5($post_key.$ch);
    $mdKey = substr($mdKey,$nh%8, $nh%8+7);
    $txt = substr($txt,1);
    $tmp = '';
    $i=0;$j=0; $k = 0;
    for ($i=0; $i<strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
        while ($j<0) $j+=66;
        $tmp .= $chars[$j];
    }

    return $tmp == base64_encode(base64_decode($tmp))?base64_decode($tmp):false;

//    return base64_decode($tmp);
}



function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null){
    $config = C('THINK_EMAIL');
    vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
    $mail             = new PHPMailer(); //PHPMailer对象
    $mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();  // 设定使用SMTP服务
    $mail->SMTPDebug  = 0;                     // 关闭SMTP调试功能
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl';                 // 使用安全协议
    $mail->Host       = $config['SMTP_HOST'];  // SMTP 服务器
    $mail->Port       = $config['SMTP_PORT'];  // SMTP服务器的端口号
    $mail->Username   = $config['SMTP_USER'];  // SMTP服务器用户名
    $mail->Password   = $config['SMTP_PASS'];  // SMTP服务器密码
    $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
    $replyEmail       = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
    $replyName        = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject    = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if(is_array($attachment)){ // 添加附件
        foreach ($attachment as $file){
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send();
}


function setUno()
{
    $u_no = 'Cj'.rand(100000,999999);
    $is_exist = M('Usere')->where(['u_no'=>$u_no])->find();
    if ($is_exist){
        setUno();
    }
    return $u_no;
}

function rand_no()
{

    $order_date = date('Y-m-d');

    //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）

    $order_id_main = date('YmdHis') ;

    //订单号码主体长度

    $order_id_len = strlen($order_id_main);

    $order_id_sum = 0;

    for($i=0; $i<$order_id_len; $i++){

        $order_id_sum += (int)(substr($order_id_main,$i,1));

    }

    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）

    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);


    return $order_id;
}

function arrayNotNull($list = array()){
    foreach ($list as $key => $value) {
        foreach ($value as $key => $val) {
            if ($val == null){
                $val = '';
            }
            $valNotNull[$key]=$val;
        }
        $arrayNotNull[] = $valNotNull;
        unset($valNotNull);

    }
    return $arrayNotNull;
}

function String2Hex($string)
{
    $hex = 0;

    for ($i = 0; $i < strlen($string); $i++) {

        $y_hex = dechex(ord($string[$i]));


        $hex  = hex_add($hex,$y_hex);

    }
    if (strlen($hex)==3){
        return strtoupper(substr($hex,1,2));
    }else{
        return strtoupper($hex);
    }
}

function hex_add($a, $b)
{

    $result = '';
    $chars = '0123456789abcdef';
    $len_a = strlen($a);
    $len_b = strlen($b);

    if ($len_a > $len_b) {
        $max = $len_a;
        $b = str_pad($b, $len_a, '0', STR_PAD_LEFT);
    } else {
        $max = $len_b;
        $a = str_pad($a, $len_b, '0', STR_PAD_LEFT);
    }

    $inc = $pos = 0;
    for ($i = $max - 1; $i >= 0; $i--) {
        $pos = hexdec($a[$i]) + hexdec($b[$i]) + $inc;
        $inc = floor($pos / 16);
        $result = $chars[$pos % 16] . $result;
    }
    if ($inc) {
        return $inc . $result;
    }
    return $result;
}

function msg_content($order,$imme)
{
    $randStr = \lyf\Str::randString(1,2);

    $len = strlen(','.$imme.','.$order)+4;

    $jx_str = String2Hex('@@'.$randStr.$len.','.$imme.','.$order);

    $send_content = '@@'.$randStr.$len.','.$imme.','.$order.$jx_str."\r\n";

    return $send_content;
}

?>